package tech.youai.ppping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.youai.nav.UrlInfo;

import java.util.Objects;

public class AlertRunner extends Thread{
    Logger logger = LoggerFactory.getLogger(AlertRunner.class);
    private final UrlPing urlPing;
    private final Weixin weixin;
    private final String name;
    private final String url;
    private Boolean ok;
    private long delay;
    private int errorCount;
    private static final long ONE_MIN= 60*1000;
    private static final long TEN_MIN= 600*1000;


    public AlertRunner(UrlPing urlPing, Weixin weixin, String name, String url) {
        this.urlPing = urlPing;
        this.weixin = weixin;
        this.name = name;
        this.url = url;
        this.delay = ONE_MIN;
    }

    @Override
    public void run() {
        while (true){
            try{
                pingAndAlert(name, url);
            }catch (Throwable ex){
                System.out.println(ex);
            }
            try {
                Thread.sleep(this.delay);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    private void pingAndAlert(String name, String url) {
        PingResult result = urlPing.ping(url);
        if(result.isSuccess()){
            errorCount = 0;
            if(this.ok==null){
                logger.info(this.name+"系统运行正常。");
            }else if(!this.ok){
                logger.info(this.name+"系统已恢复正常。");
            }

            //如果没问题，则1分钟后再检查
            this.delay = ONE_MIN;
        }else{
            errorCount++;
            logger.warn(this.name+"系统无法访问!!!!!!!");
            if(errorCount>1){
                //如果有问题，则10分钟后再检查
                this.delay = TEN_MIN;
                this.weixin.noticeUser("ayi", "["+name+"]警报警报！", name+"无法登录！(10分钟后再次检查)", new UrlInfo(url));

            }

        }
        this.ok = result.isSuccess();
    }
}
